﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using IntraVision.Web;
using IntraVision.Web.Security;
using Model;

[AllowedRole("IsAdmin")]
public class RoleController : EntityTableController<Role,NotarialServiceDataContext>
{
    protected override void EntityLoaded(NotarialServiceDataContext dc, Role role)
    {
        ViewData["permissions"] = (from up in role.RolePermissions orderby up.Permission.PermissionGroup.Id select up.PermissionId).ToArray();
        ViewData["groups"] = (from g in dc.PermissionGroups orderby g.Id select g).ToList();
    }

    protected override void BeforeSubmit(NotarialServiceDataContext dc, Role role)
    {
        #region Сохранить полномочия
        if (!string.IsNullOrEmpty(Request["pid"]))
        {
            int[] ids = RequestHelper.GetIdsFromString(Request["pid"]);

            if (ids.Length == 0)
                dc.RolePermissions.DeleteAllOnSubmit(role.RolePermissions);
            else
            {
                dc.RolePermissions.DeleteAllOnSubmit((from p in role.RolePermissions where !ids.Contains(p.PermissionId) select p));
                int[] exids = (from up in role.RolePermissions select up.PermissionId).ToArray();
                foreach (int id in ids)
                {
                    if (!exids.Contains(id))
                    {
                        var up = new RolePermission();
                        up.PermissionId = id;
                        role.RolePermissions.Add(up);
                    }
                }
            }
        }
        #endregion
    }
}
